package dd.server;

import java.util.ArrayList;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import server.ClientState;
import server.Server;
import xml.Message;
import dd.model.Edge;
import dd.model.Event;
import dd.model.serverModel;

public class addEdgeResponseController {
	public Message process(ClientState client, Message request) {
		serverModel sm = serverModel.getInstance();
		Event e = sm.getEvent();
		Node update = request.contents.getFirstChild();
		NamedNodeMap map = update.getAttributes();
		//get information
		String geteventid = map.getNamedItem("id").getNodeValue();
		String leftt = map.getNamedItem("left").getNodeValue();
		int left = Integer.parseInt(leftt);
		String rightt = map.getNamedItem("right").getNodeValue();
		int right = Integer.parseInt(rightt);
		String heightt = map.getNamedItem("height").getNodeValue();
		int height = Integer.parseInt(heightt);
		System.out.println("received: "+leftt+" "+rightt+" "+heightt);
		ArrayList<Edge> ledge = e.getedgelist();
		Edge edge = new Edge();
		edge.setEdge(left, right, height);
		ledge.add(edge);
		e.setedgelist(ledge);
		// Construct message reflecting state
		String xmlString = Message.responseHeader(request.id()) +
				 "<addEdgeResponse id='"+geteventid+"' left='"+leftt+"' right='"
				+rightt+"' height='"+heightt+"'>"+"</addEdgeResponse></response>";
		Message m =new Message(xmlString);
		//send this response to all the client
		for(String id :Server.ids()){
			if (!id.equals(client.id())) {
				Server.getState(id).sendMessage(m);
			}
		}

		// send this response back to the client which sent us the request.
		return m;
}
}
